package com.socene.kotlin.config.security

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.security.SecurityProperties
import org.springframework.context.annotation.Bean
import org.springframework.core.annotation.Order
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException

/**
 *Created by: Sorata 2017/9/9 下午6:25
 *
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启注解
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
class WebAppSecurityConfig : WebSecurityConfigurerAdapter() {

    /*添加拦截规则*/
    override fun configure(http: HttpSecurity?) {
        http?.headers()?.disable()?.
                csrf()?.disable()?.
                authorizeRequests()?.mvcMatchers("/admin/*")?.permitAll()?.
                mvcMatchers("/web/*")?.authenticated()?.
                mvcMatchers("/admin/login.html")?.authenticated()?.
                anyRequest()?.permitAll()?.
                and()?.
                formLogin()?.loginPage("/admin/index.html")?.
                successForwardUrl("/success")?.failureForwardUrl("/fail")
    }

    /*添加用户的服务的实现*/
    override fun configure(auth: AuthenticationManagerBuilder?) {
        auth?.userDetailsService(securityDetailsService)
    }

    @Autowired lateinit var securityDetailsService: WebSecurityUserDetailsService

    @Bean
    fun webSecurityUserDetailsService(): WebSecurityUserDetailsService {
        return WebSecurityUserDetailsService()
    }


}

/* 配置用户登录服务  这里需要与数据库进行交互*/
class WebSecurityUserDetailsService : UserDetailsService {


    override fun loadUserByUsername(username: String?): UserDetails {

        if (null == username) throw UsernameNotFoundException("Not Found User")
        if (username == "admin") {
            return SysUserDetails(username, "", "admin", arrayOf("admin", "user"))
        }
        throw UsernameNotFoundException("Not Found User")
    }
}